package fr.univ.lille1.server.utils;

import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Utils {

	private Utils() {

	}

	/**
	 * Convert a string into an hashed string using the MD5 algorithm.
	 * 
	 * @param the
	 *            input string. .
	 * @return the hashed string.
	 */
	public static String md5(String input) {

		String md5 = null;

		if (input == null) {
			return null;
		}

		try {

			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(input.getBytes(Charset.forName("UTF-8")), 0,
					input.length());
			final int hexa = 16;
			md5 = new BigInteger(1, digest.digest()).toString(hexa);

		} catch (NoSuchAlgorithmException e) {

			return null;
		}
		return md5;
	}

	/**
	 * Validate mail with regular expression
	 * 
	 * @param mail
	 *            mail for validation
	 * @return true valid mail, false invalid mail
	 */
	public static boolean validateMail(final String mail) {
		Pattern pattern = Pattern.compile(Constants.EMAIL_PATTERN);
		Matcher matcher = pattern.matcher(mail);
		return matcher.matches();
	}
	
	/**
	 * Check if the given string is null or empty.
	 * @param s
	 * @return true is the string is valid, false otherwise
	 */
	public static boolean checkString(String s){
		if(s == null){
			return false;
		}
		if(s.trim().isEmpty()){
			return false;
		}
		return true;
	}
	
	public static boolean checkObject(Object o){
		return o != null;
	}
	
}
